package com.yuzhenxin.bookstore.web.servlet;

import com.yuzhenxin.bookstore.domain.Book;
import com.yuzhenxin.bookstore.domain.Cart;
import com.yuzhenxin.bookstore.domain.CartItem;
import com.yuzhenxin.bookstore.domain.User;
import com.yuzhenxin.bookstore.service.BookService;
import com.yuzhenxin.bookstore.tools.servlet.BaseServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/CartServlet")
public class CartServlet extends BaseServlet {
    /**
     * 添加购物条目
     */
    public String add(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("session_user");
        if (user == null) {
            response.getWriter().println("""
                    <script language="JavaScript">
                    \talert("You are not logged in yet, please log in first!")
                    </script>
                    """);
            return "";
        }

        Cart cart = (Cart) request.getSession().getAttribute("cart");
        /*
         * 表单传递的只有bid和数量
         * 2、得到条目
         * >得到图书和数量
         * >先得到图书的bid，查询数据库得到Book
         * >数量表单中有
         */
        String bid = request.getParameter("bid");
        Book book = new BookService().load(bid);
        int count = Integer.parseInt(request.getParameter("count"));

        CartItem cartItem = new CartItem();
        cartItem.setBook(book);
        cartItem.setCount(count);

        cart.add(cartItem);
        return "f:/jsps/cart/list.jsp";
    }

    public String clear(HttpServletRequest request)
            throws ServletException, IOException {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        cart.clear();
        return "f:/jsps/cart/list.jsp";
    }

    public String delete(HttpServletRequest request) {
        /*
         * 1、得到车
         * 2、得到要删除的bid
         */
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        String bid = request.getParameter("bid");
        cart.delete(bid);
        return "f:/jsps/cart/list.jsp";
    }
}
